package com.kb.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kb.common.MeException;
import com.kb.dto.InvoiceSearchDTO;
import com.kb.dto.crm.CrmDocumentEntity;
import com.kb.dto.other.CrmWaitInvoiceData;
import com.kb.dto.other.CrmWaitInvoiceDetails;
import com.kb.dto.other.InvoiceSearch;
import com.kb.entity.crm.Invoice;
import com.kb.mapper.pg.CrmToK3Mapper;
import com.kb.service.K3Service;
import com.kb.service.flow.FlowService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

@DS("SmartQuote_kb_live")
@Service
public class K3ServiceImpl implements K3Service {

    @Resource
    private CrmToK3Mapper mapper;
    @Resource
    private FlowService flowService;

    @Override

    public List<CrmWaitInvoiceData> queryWaitInvoiceList(InvoiceSearch invoiceSearchDTO) {
        //查询待开票列表数据
        LambdaQueryWrapper<Invoice> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Invoice::getStatus, "Confirmed");
        // 设置时间范围：如果为空，默认查询今年的数据
        LocalDate startDate = invoiceSearchDTO.getStartDate();
        LocalDate endDate = invoiceSearchDTO.getEndDate();

        if (startDate == null || endDate == null) {
            // 获取当前年份
            LocalDate now = LocalDate.now();
            int currentYear = now.getYear();
            startDate = LocalDate.of(currentYear, 1, 1);  // 今年第一天
            endDate = LocalDate.of(currentYear, 12, 31);  // 今年最后一天
        }
        //组织字段转义
        if (invoiceSearchDTO.getSaleOrg() != null){
            String saleCode = flowService.querySaleCode(invoiceSearchDTO.getSaleOrg());
            if (Objects.isNull(saleCode)){
                throw new MeException("销售组织不存在");
             }
            invoiceSearchDTO.setSaleOrg(saleCode);
        }


        List<Invoice> invoices = mapper.queryInvoiceList(invoiceSearchDTO);

        if (CollectionUtils.isNotEmpty(invoices)) {
            List<CrmWaitInvoiceData> crmWaitInvoiceData = BeanUtil.copyToList(invoices, CrmWaitInvoiceData.class);
            for (CrmWaitInvoiceData crmWaitInvoiceDatum : crmWaitInvoiceData) {
                //检验文件是否存在  crm系统bug 文件删除  文件id不会清空
                if (StringUtils.isBlank(crmWaitInvoiceDatum.getAttachId())){
                    crmWaitInvoiceDatum.setFileId(null);
                }
                //拆分开票地址和电话 以 "/"拆分
                if (StringUtils.isNotBlank(crmWaitInvoiceDatum.getBillingAdd())){
                    String[] split = crmWaitInvoiceDatum.getBillingAdd().split("/");
                    crmWaitInvoiceDatum.setBillingAdd(split[0].trim());
                    if (split.length > 1) {
                        crmWaitInvoiceDatum.setBillingTelephone(split[1].trim());
                    }
                }
                List<CrmWaitInvoiceDetails> crmWaitInvoiceDetails = mapper.queryWaitInvoiceList(crmWaitInvoiceDatum.getRecId());
                if (CollectionUtils.isNotEmpty(crmWaitInvoiceDetails) && StringUtils.isNotBlank(crmWaitInvoiceDetails.get(0).getTradeRouteDesc())) {
                    crmWaitInvoiceDatum.setTradeRouteDesc(crmWaitInvoiceDetails.get(0).getTradeRouteDesc());
                }
                //查询扣款信息
                List<CrmWaitInvoiceDetails> creditMemoList = mapper.queryCreditMemoList(crmWaitInvoiceDatum.getRecId());
                if (CollectionUtils.isNotEmpty(creditMemoList)) {
                    crmWaitInvoiceDetails.addAll(creditMemoList);
                 }
                // 合并相同salesOrder和arNo的数据
                List<CrmWaitInvoiceDetails> mergedDetails = mergeInvoiceDetails(crmWaitInvoiceDetails);
                //去掉"totalAmount": "0.0"的数据
                mergedDetails.removeIf(detail -> "0.0".equals(detail.getTotalAmount()));
                crmWaitInvoiceDatum.setDetails(mergedDetails);
//                crmWaitInvoiceDatum.setDetails(crmWaitInvoiceDetails);
            }
            return crmWaitInvoiceData;
        }
        return new ArrayList<>();
    }
    /**
     * 合并相同salesOrder的发票明细
     * @param details 原始发票明细列表
     * @return 合并后的发票明细列表
     */
    private List<CrmWaitInvoiceDetails> mergeInvoiceDetails(List<CrmWaitInvoiceDetails> details) {
        if (CollectionUtils.isEmpty(details)) {
            return details;
        }

        // 使用Map来分组，key为salesOrder
        Map<String, CrmWaitInvoiceDetails> mergedMap = new LinkedHashMap<>();
        Map<String, Set<String>> arNoSetMap = new HashMap<>();

        for (CrmWaitInvoiceDetails detail : details) {
            String key = detail.getSalesOrder();

            if (mergedMap.containsKey(key)) {
                // 如果已存在，则合并数值字段
                CrmWaitInvoiceDetails existingDetail = mergedMap.get(key);

                // 合并数量和各种费用字段
                existingDetail.setQuantity(addStringNumbers(existingDetail.getQuantity(), detail.getQuantity()));
                existingDetail.setEngFee(addStringNumbers(existingDetail.getEngFee(), detail.getEngFee()));
                existingDetail.setFilmFee(addStringNumbers(existingDetail.getFilmFee(), detail.getFilmFee()));
                existingDetail.setToolFee(addStringNumbers(existingDetail.getToolFee(), detail.getToolFee()));
                existingDetail.setPnlFee(addStringNumbers(existingDetail.getPnlFee(), detail.getPnlFee()));
                existingDetail.setRushFee(addStringNumbers(existingDetail.getRushFee(), detail.getRushFee()));
                existingDetail.setOtherFee(addStringNumbers(existingDetail.getOtherFee(), detail.getOtherFee()));
                existingDetail.setAddFeeing(addStringNumbers(existingDetail.getAddFeeing(), detail.getAddFeeing()));
                existingDetail.setTotalAmount(addStringNumbers(existingDetail.getTotalAmount(), detail.getTotalAmount()));

                // 收集arNo用于拼接
               if(!Objects.equals("1", detail.getDocType())){
                   arNoSetMap.get(key).add(detail.getArNo());
               }
            } else {
                // 如果不存在，则直接放入
                mergedMap.put(key, detail);
                // 初始化arNo集合
                Set<String> arNoSet = new LinkedHashSet<>();
                arNoSet.add(detail.getArNo());
                arNoSetMap.put(key, arNoSet);
            }
        }

        // 处理arNo拼接
        for (Map.Entry<String, CrmWaitInvoiceDetails> entry : mergedMap.entrySet()) {
            String salesOrder = entry.getKey();
            CrmWaitInvoiceDetails detail = entry.getValue();
            Set<String> arNos = arNoSetMap.get(salesOrder);
            if (arNos != null && !arNos.isEmpty()) {
                detail.setArNo(String.join(",", arNos));
            }
        }

        return new ArrayList<>(mergedMap.values());
    }


    /**
     * 安全地将两个字符串数字相加
     * @param num1 第一个数字字符串
     * @param num2 第二个数字字符串
     * @return 相加后的结果字符串
     */
    private String addStringNumbers(String num1, String num2) {
        if (StringUtils.isBlank(num1) && StringUtils.isBlank(num2)) {
            return "0";
        }
        if (StringUtils.isBlank(num1)) {
            return StringUtils.isBlank(num2) ? "0" : num2;
        }
        if (StringUtils.isBlank(num2)) {
            return num1;
        }

        try {
            double d1 = Double.parseDouble(num1);
            double d2 = Double.parseDouble(num2);
            return String.valueOf(d1 + d2);
        } catch (NumberFormatException e) {
            return "0";
        }
    }
    @Override
    public CrmDocumentEntity queryDocument(String fileId) {
        return mapper.queryDocument(fileId);
    }

    @Override
    public boolean updateInvoiceInfo(Invoice invoice) {
        String taxInvoiceNo = invoice.getTaxInvoiceNo();
        if (StringUtils.isBlank(taxInvoiceNo)){
            throw new MeException("发票编号不能为空");
        }
        //先查询该发票是否有值，有则拼接更新，无则插入
        Invoice queryInvoice = mapper.queryInvoiceByInvoiceNumber(invoice.getInvoiceNumber());
        if (queryInvoice == null){
            throw new MeException("此发票已不存在，请联系管理员");
        }
        if (StringUtils.isNotBlank(queryInvoice.getTaxInvoiceNo())) {
            String existingTaxInvoiceNo = queryInvoice.getTaxInvoiceNo();
            // 检查新的taxInvoiceNo是否已经存在于原有的taxInvoiceNo中
            String queryInvoiceTaxInvoiceNo = queryInvoice.getTaxInvoiceNo();
            if (!queryInvoiceTaxInvoiceNo.contains(taxInvoiceNo)) {
                invoice.setTaxInvoiceNo(existingTaxInvoiceNo + "," + taxInvoiceNo);
            } else {
                invoice.setTaxInvoiceNo(existingTaxInvoiceNo);
            }
        }
        UpdateWrapper<Invoice> update = new UpdateWrapper<>();
        update.eq("InvoiceNumber", invoice.getInvoiceNumber());
        invoice.setStatus("Invoice");
        invoice.setBillingNotes("k3开票同步: "+ DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss"));
        return mapper.update(invoice, update) > 0;
    }

}
